package cpr.command;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;

import cpr.DefaultCommandHandler;
import cpr.Printer;
import data.IWorksetItem;

public class CmdWorksetSave extends DefaultCommandHandler {
	public CmdWorksetSave() {
		super("ws-save");
	}
	public void execute(String[] params) throws Exception {
		String filename = getCommandContext().getContext().getCurrentWorksetContext().getWorksetFilePath();
		Printer.println("Saving "+filename);
		
		File file = new File(filename);
		if (file.exists()) {
			file.delete();
		}
		Writer w = new FileWriter(file);
		BufferedWriter bw = new BufferedWriter(w);
		
		List items = getCommandContext().getContext().getCurrentWorksetContext().getWorksetItems();
		StringBuffer sb = new StringBuffer();
		for (Iterator iter = items.iterator(); iter.hasNext();) {
			IWorksetItem item = (IWorksetItem) iter.next();
			if (item.getClusterDescriptor().getRule()!=null) {
				printWorkItem(item,sb);
			}
		}
		bw.write(sb.toString());
		bw.close();
	}
	private void printWorkItem(IWorksetItem item, StringBuffer sb) {
		sb.append(""+item.getClusterDescriptor().getRule().ruleNrGlobal);
		sb.append("\t");
		sb.append(""+item.getClusterDescriptor().getVector().score);
		sb.append("\t");
		sb.append(""+item.getClusterDescriptor().getSize());
		sb.append("\n");
		return;
	}
} 

